package com.vodone.v1pin.core.service
{
	
	import com.vodone.v1pin.core.service.json.MYJSON;
	
	import mx.rpc.IResponder;
	import mx.rpc.events.ResultEvent;
	
	public class JsonResponder implements IResponder
	{
		private var resultHandler:Function;
		private var faultHandler:Function;
		private var handlerArgs:Array;
		
		public function JsonResponder( resultHandler:Function, faultHandler:Function = null, handlerArgs:Array = null )
		{
			this.resultHandler = resultHandler;
			this.faultHandler = faultHandler;
			this.handlerArgs = handlerArgs;
		}
		public function result( data:Object ):void
		{
			if(null == resultHandler)return;
			var resultEvent:ResultEvent = data as ResultEvent;
			var obj:Object = {};
			try
			{
				obj = MYJSON.decode( resultEvent.result as String );
			}
			catch( e:Error ){};
			
			if( handlerArgs == null )
			{
				resultHandler( obj );
			}
			else
			{
				resultHandler.apply( null, [ obj ].concat( handlerArgs ) );
			}
		}
		
		public function fault(info:Object):void
		{
			if( faultHandler != null )
			{
				if( handlerArgs == null )
				{
					faultHandler( info );
				}
				else
				{
					try
					{
						faultHandler( info );
					}
					catch( e:Error )
					{
						faultHandler.apply( null, [ info ].concat( handlerArgs ) );
					}
				}
			}
			else
			{
				// todo: what if there is no fault handler applied to dynamic responder
				// ben says fails silently, maybe logging is smarter...
			}
		}

	}
}